#include "sensor.h"

// Prints out a given error.
void error(const char *msg) { perror(msg); }

void *repository(void *t_id) {
  int id = (int) t_id;
  struct sockaddr_in serv_addr;  // Hold address. 
  struct hostent *server;        // Server info.
  char data[BSIZE];

  // Listen.
  server = gethostbyname("localhost");
  if (server == NULL) fprintf(stderr, "No such host.");
  bzero((char *) &serv_addr, sizeof(serv_addr));   
  bcopy((char *) server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
  int receiving_sock = socket(AF_INET, SOCK_DGRAM, FLAGS);
  if (FAILURE == receiving_sock) SOCK_ERROR;
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port   = htons(PORT+id);
  if (bind(receiving_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) == FAILURE) BIND_ERROR;
  listen(receiving_sock,5);
  socklen_t serv_len = sizeof(serv_addr);
  int listening_sock = accept(receiving_sock, (struct sockaddr *) &serv_addr, &serv_len);
  if (listening_sock == FAILURE) ACPT_ERROR;
  bzero(data, BSIZE);
  while (read(listening_sock, data, BSIZE) != FAILURE) {
    // TODO: Create handler thread.
  }
  return;
}

int main () {
  int i;
  pthread_t thread[NUM_TOTAL];

  // Create repository threads; then wait until they all finish.
  for (i=RBEG; i<REND; i++) pthread_create((pthread_t *) thread[i], NULL, repository, (void *) i); 
  for (i=TBEG; i<TEND; i++) pthread_join  (              thread[i],                   NULL);

  return 0;
}
